#!/usr/bin/env python
# coding=utf8

# Copyright 1999-2017 Alibaba Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

assert sys.version_info[0] == 2 and sys.version_info[1] == 7, "Need Python 2.7"
reload(sys)
if hasattr(sys, "setdefaultencoding"):
    sys.setdefaultencoding("UTF-8")

import os

sys.path.append(os.path.abspath(os.path.dirname(__file__)))
vendor_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "vendor"))
sys.path.append(vendor_dir)
for file_path in os.listdir(vendor_dir):
    if file_path.endswith(".egg"):
        sys.path.append(os.path.join(vendor_dir, file_path))

from component import paramparser
from component import log
import env

import threading
import time

import core
from core import fetcher
from component import constants
from component import fileutil
from component import httputil
from component import netutil
from component import stdshower

log.init_log(log.LOG_NAME_CLIENT)
logger = log.client_logger
logger.info("cmd params:%s,python version:%s", paramparser.cmdparam, sys.version_info)


def download(params):
    finished = threading.Event()
    result = {"success": False}
    try:
        params.update({"finished": finished, "result": result})

        if env.back_reason > 0:
            getter = fetcher.BackDownloader(finished, result)
        else:
            getter = fetcher.P2PDownloader(params["node"], params["taskId"], params["nodes"], params["url"],
                                           params["port"], finished, result)

        getter.setDaemon(True)
        getter.start()

        timeout = 5 * 60
        if not paramparser.cmdparam.timeout:
            if env.file_length > 0:
                timeout = env.file_length / (64 * 1024) + 10.0
        else:
            timeout = paramparser.cmdparam.timeout

        finished.wait(timeout)

        if not finished.isSet():
            logger.error("download timeout(%ds)", timeout)
            stdshower.StdShower.print_info("download timeout(%ds)" % timeout)

        if env.file_length < 0:
            if env.real_target and os.path.isfile(env.real_target):
                env.file_length = os.path.getsize(env.real_target)

        end_time = time.time()
        if "port" in params and params["port"] > 0:
            result_log = {"taskId": getter.task_id, "cid": env.cid, "superNode": getter.node,
                          "taskFileName": env.task_file_name}

            netutil.request_local(params["port"], constants.LOCAL_HTTP_PATH_CLIENT, "finish",
                                  result_log)
        logger.info("|%s|%s|%d|%d|%s|%s|%.3f|", getter.task_id, paramparser.cmdparam.url, env.file_length,
                    getter.total, getter.node, env.call_system, end_time - env.start_time)
    except Exception, e1:
        logger.exception("download error")
        stdshower.StdShower.print_info(e1.message)

    try:
        fileutil.delete_file(env.branch_target)
        if env.client_in_user or env.data_dir == env.system_data_dir:
            fileutil.delete_file(core.get_task_file(env.task_file_name))
        if env.service_in_user:
            if "port" in params and params["port"] > 0:
                httputil.http_request.down_service(getter.task_id, env.cid, getter.node)
            fileutil.delete_file(core.get_service_file(env.task_file_name))
    except:
        logger.exception("clean temp files error")

    logger.info("download %s cost:%.3fs length:%d reason:%d", "SUCCESS" if result["success"] else "FAIL",
                time.time() - env.start_time, env.file_length, env.back_reason)

    stdshower.StdShower.finish()

    # close session
    httputil.http_request.close()

    return result["success"]


if __name__ == "__main__":
    exit_code = 1
    try:
        stdshower.StdShower.print_info("dfget version:%s" % constants.VERSION)
        stdshower.StdShower.print_info("workspace:%s sign:%s" % (env.usr_home, env.execute_sign))
        register_result = {}
        try:
            register_result = env.init()
            if register_result:
                stdshower.StdShower.print_info("client:%s connected to node:%s" % (env.ip, register_result["node"]))
                stdshower.StdShower.print_info("init success...")
                stdshower.StdShower.print_info("start download by dragonfly")
        except SystemExit:
            raise
        except Exception, e:
            logger.exception("init fail but try back down")
            stdshower.StdShower.print_info(e.message)
            if env.back_reason == constants.REASON_NONE:
                env.back_reason = constants.REASON_INIT_ERROR

        if download(register_result):
            exit_code = 0
    except SystemExit, e:
        if hasattr(e, "code"):
            exit_code = e.code
    except Exception, e:
        logger.exception("panic......")
        stdshower.StdShower.print_info(e.message)
    if exit_code == 0:
        stdshower.StdShower.print_info("download SUCCESS(0) cost(%.3fs) length:%d reason:%d" % (
            time.time() - env.start_time, env.file_length, env.back_reason))
    else:
        stdshower.StdShower.print_info("download FAIL(%d) cost(%.3fs) length:%d reason:%d" % (exit_code,
                                                                                              time.time() - env.start_time,
                                                                                              env.file_length,
                                                                                              env.back_reason))
    sys.exit(exit_code)
